package com.crm.system.service.impl.index;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.beust.jcommander.internal.Lists;
import com.crm.common.model.DhPageInfo;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.DateUtils;
import com.crm.dao.mapper.customMapper.customerManagerCustomMapper.CustomerPayCustomMapper;
import com.crm.dao.mapper.customMapper.sys.UserAccountCustomMapper;
import com.crm.model.dto.SalesmanDto;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.customerManager.CompanyPayMoneyVO;
import com.crm.model.vo.customerManager.CustomerPayMoneyVO;
import com.crm.model.vo.finishOrderProduct.FinishOrderProductVO;
import com.crm.model.vo.index.PerformanceStatisticsVO;
import com.crm.model.vo.index.PerformanceVO;
import com.crm.model.vo.index.ProductVO;
import com.crm.model.vo.index.RankingVO;
import com.crm.model.vo.opportunityManager.PerformanceRankingVO;
import com.crm.redis.RedisPrefix;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.service.index.FirstPageDbService;
import com.crm.system.service.index.FirstPageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页信息
 */
@Slf4j
@Service
public class FirstPageServiceImpl implements FirstPageService {

    @Autowired
    private FirstPageDbService firstPageDbService;

    @Autowired
    private CustomerPayCustomMapper customerPayCustomMapper;

    @Autowired
    private UserAccountCustomMapper userAccountCustomMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    private static String accountId = "71902468-8dee-4e30-b554-456d2140c7d9";

    /**
     * 首页统计信息  都是用户下的
     *
     * @param dateType thisMonth 本月 thisLastMonth 上月 thisYear 本年
     * @param bs       1数据一览  2销售简报
     * @return
     */
    @Override
    public Map<String, Object> firstPageContent(String dateType, String bs) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> map = new HashMap<>();

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("thisLastMonth".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
            if ("thisYear".equals(dateType)) {
                //本年
                dateUnit = 3;
            }
        }

        if ("1".equals(bs)) {

            //业绩排名
            RankingVO rankingVO = firstPageDbService.selectRanking(userAccount.getAccountId(), dateUnit);
            RankingVO rankingVOLast = firstPageDbService.selectRanking(userAccount.getAccountId(), dateUnit + 1);


            //会员数
            Integer customerMembershipNumber = firstPageDbService.selectCustomerMembershipNumber(userAccount.getAccountId(), dateUnit);
            if (customerMembershipNumber == null) {
                customerMembershipNumber = 0;
            }
            Integer customerMembershipNumberLast = firstPageDbService.selectCustomerMembershipNumber(userAccount.getAccountId(), dateUnit + 1);
            if (customerMembershipNumberLast == null) {
                customerMembershipNumberLast = 0;
            }
            Integer customerMembershipNumberTrend = compare(customerMembershipNumber, customerMembershipNumberLast);


            //联系人数
            Integer contactNumber = firstPageDbService.selectContactNumber(userAccount.getAccountId(), dateUnit, userAccount.getCompanyId());
            if (contactNumber == null) {
                contactNumber = 0;
            }
            Integer contactNumberLast = firstPageDbService.selectContactNumber(userAccount.getAccountId(), dateUnit + 1, userAccount.getCompanyId());
            if (contactNumberLast == null) {
                contactNumberLast = 0;
            }
            Integer contactNumberTrend = compare(contactNumber, contactNumberLast);

            //商机数
            Integer opportunityNumber = firstPageDbService.selectOpportunityNumber(userAccount.getAccountId(), dateUnit);
            if (opportunityNumber == null) {
                opportunityNumber = 0;
            }
            Integer opportunityNumberLast = firstPageDbService.selectOpportunityNumber(userAccount.getAccountId(), dateUnit + 1);
            if (opportunityNumberLast == null) {
                opportunityNumberLast = 0;
            }
            Integer opportunityNumberTrend = compare(opportunityNumber, opportunityNumberLast);

            //电话总时长
            Integer totalTelehoneHours = firstPageDbService.selectTotalTelehoneHours(userAccount.getAccountId(), dateUnit);
            if (totalTelehoneHours == null) {
                totalTelehoneHours = 0;
            }
            Integer totalTelehoneHoursLast = firstPageDbService.selectTotalTelehoneHours(userAccount.getAccountId(), dateUnit + 1);
            if (totalTelehoneHoursLast == null) {
                totalTelehoneHoursLast = 0;
            }
            Integer totalTelehoneHoursTrend = compare(totalTelehoneHours, totalTelehoneHoursLast);

            //提成总金额
            BigDecimal royaltyMoneyTotal = firstPageDbService.selectRoyaltyMoneyTotal(userAccount.getAccountId(), dateUnit);
            if (royaltyMoneyTotal == null) {
                royaltyMoneyTotal = new BigDecimal(0);
            }
            BigDecimal royaltyMoneyTotalLast = firstPageDbService.selectRoyaltyMoneyTotal(userAccount.getAccountId(), dateUnit + 1);
            if (royaltyMoneyTotalLast == null) {
                royaltyMoneyTotalLast = new BigDecimal(0);
            }
            Integer royaltyMoneyTotalTrend = compareBigDecimal(royaltyMoneyTotal, royaltyMoneyTotalLast);

            //业绩排名
            if (rankingVO == null || rankingVO.getRankingNumber() == null) {
                map.put("rankingNumber", 0);
            } else {
                map.put("rankingNumber", rankingVO.getRankingNumber());
            }

            Integer rankingNumber = (Integer) map.get("rankingNumber");
            if (rankingNumber == null) {
                rankingNumber = 0;
            }

            //业绩排名
            if ("thisMonth".equals(dateType) || "thisLastMonth".equals(dateType)) {
                if (rankingVOLast == null || rankingVOLast.getRankingNumber() == null) {

                    Integer rankingNumberTrend = compare(rankingNumber, 0);
                    map.put("rankingNumberTrend", rankingNumberTrend);
                } else {
                    Integer rankingNumberTrend = compare(rankingNumber, rankingVOLast.getRankingNumber());
                    map.put("rankingNumberTrend", rankingNumberTrend);
                }
                map.put("customerMembershipNumberTrend", customerMembershipNumberTrend);
                map.put("contactNumberTrend", contactNumberTrend);
                map.put("opportunityNumberTrend", opportunityNumberTrend);
                map.put("totalTelehoneHoursTrend", totalTelehoneHoursTrend);
                map.put("royaltyMoneyTotalTrend", royaltyMoneyTotalTrend);
            }


            //会员数
            map.put("customerMembershipNumber", customerMembershipNumber);
            //联系人数
            map.put("contactNumber", contactNumber);
            //商机数
            map.put("opportunityNumber", opportunityNumber);
            //电话总时长
            map.put("totalTelehoneHours", totalTelehoneHours);
            //提成总金额
            map.put("royaltyMoneyTotal", royaltyMoneyTotal);


        }

        //7天逾期未联系的客户数量
//        Integer beOverdueCustomerNumber = firstPageDbService.selectBeOverdueCustomerNumber(userAccount.getAccountId(),pastDate);
//        map.put("beOverdueCustomerNumber",beOverdueCustomerNumber);

        //7天内新增跟进
//        Integer addFollowNumber = firstPageDbService.selectAddFollowNumber(userAccount.getAccountId(),pastDate);
//        map.put("addFollowNumber",addFollowNumber);


        if ("2".equals(bs)) {

            //新增订单
            Integer addOrderNumber = firstPageDbService.selectAddOrderNumber(userAccount.getAccountId(), dateUnit);
            if (addOrderNumber == null) {
                addOrderNumber = 0;
            }
            Integer addOrderNumberLast = firstPageDbService.selectAddOrderNumber(userAccount.getAccountId(), dateUnit + 1);
            if (addOrderNumberLast == null) {
                addOrderNumberLast = 0;
            }
            Integer addOrderNumberTrend = compare(addOrderNumber, addOrderNumberLast);


            //新增业绩
            BigDecimal addAchievementNumber = firstPageDbService.selectAddAchievement(userAccount.getAccountId(), dateUnit);
            if (addAchievementNumber == null) {
                addAchievementNumber = new BigDecimal(0);
            }
            BigDecimal addAchievementNumberLast = firstPageDbService.selectAddAchievement(userAccount.getAccountId(), dateUnit + 1);
            if (addAchievementNumberLast == null) {
                addAchievementNumberLast = new BigDecimal(0);
            }
            Integer addAchievementNumberTrend = compareBigDecimal(addAchievementNumber, addAchievementNumberLast);

            //新增拜访
            Integer addFollowVisitNumber = firstPageDbService.selectAddFollowVisitNumber(userAccount.getAccountId(), dateUnit);
            if (addFollowVisitNumber == null) {
                addFollowVisitNumber = 0;
            }
            Integer addFollowVisitNumberLast = firstPageDbService.selectAddFollowVisitNumber(userAccount.getAccountId(), dateUnit + 1);
            if (addFollowVisitNumberLast == null) {
                addFollowVisitNumberLast = 0;
            }
            Integer addFollowVisitNumberTrend = compare(addFollowVisitNumber, addFollowVisitNumberLast);

            //新增订单
            map.put("addOrderNumber", addOrderNumber);
            //新增业绩
            map.put("addAchievementNumber", addAchievementNumber);
            //新增拜访
            map.put("addFollowVisitNumber", addFollowVisitNumber);


            if ("thisMonth".equals(dateType) || "thisLastMonth".equals(dateType)) {
                map.put("addOrderNumberTrend", addOrderNumberTrend);
                map.put("addAchievementNumberTrend", addAchievementNumberTrend);
                map.put("addFollowVisitNumberTrend", addFollowVisitNumberTrend);
            }
        }

        return map;
    }

    /**
     * 对比大小
     *
     * @param addOrderNumber     本月
     * @param addOrderNumberLast 上个月
     * @return
     */
    public Integer compare(Integer addOrderNumber, Integer addOrderNumberLast) {
        if (addOrderNumber > addOrderNumberLast) {
            return 1;  //1上升
        } else {
            return 2;  //2 相等和小于都是下降
        }
    }

    public Integer compareBigDecimal(BigDecimal number, BigDecimal numberLast) {
        if (number.compareTo(numberLast) == 1) {
            return 1;
        } else if (number.compareTo(numberLast) == -1) {
            return 2;
        } else if (number.compareTo(numberLast) == 0) {
            return 2;
        } else {
            return 2;
        }
    }

    /**
     * 首页统计个人业绩排行榜 (reids)
     *
     * @param dateType    1年 2年月
     * @param combination dateType 1 2021  2 202101
     * @return
     */
    @Override
    public Map<String, Object> personalPerformanceRankingRedis(String dateType, String combination) {
        Map<String, Object> map = new HashMap<>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Integer ranking = 0;
        String key = RedisPrefix.SALESMAN_TOP_THIRTY;
        if ("1".equals(dateType)) {
            key = RedisPrefix.SALESMAN_TOP_YEAR_THIRTY + combination;
        } else if ("2".equals(dateType)) {
            key = RedisPrefix.SALESMAN_TOP_MONTH_THIRTY + combination;
        }

        int page = 0;
        List<PerformanceRankingVO> list = new ArrayList<>();

        list = ValueRMapper.getRedisObjectList(redisTemplate, key, PerformanceRankingVO.class);

        if (list != null && list.size() > 0) {
            if (list.size() > 30) {
                page = 30;
            } else {
                page = list.size();
            }
        }

        if (Objects.nonNull(list)) {
            list = list
                    .stream()
                    .sorted(Comparator.comparing(PerformanceRankingVO::getContractActualTotalAmount).reversed())
                    .collect(Collectors.toList());

            for (int i = 0; i < list.size(); i++) {
                PerformanceRankingVO t = list.get(i);
                if (t.getAccountId().equals(userAccount.getAccountId())) {
                    ranking = i + 1;
                }
            }

            list = list.subList(0, page);
        }

        //log.info(ranking.toString());


        if (list == null) {
            list = new ArrayList<>();
        }

        map.put("list", list);
        map.put("ranking", ranking);

        return map;
    }

    /**
     * 首页统计个人业绩排行榜
     *
     * @param dateType    1年 2年月
     * @param combination dateType 1 2021  2 202101
     * @return
     */
    @Override
    public Map<String, Object> personalPerformanceRankingList(String dateType, String combination) {
        Map<String, Object> map = new HashMap<>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String ranking = "0";
        Integer dateUnit = 0;

        if (!StringUtils.isBlank(dateType)) {
            if ("1".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("2".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
        }
        List<PerformanceRankingVO> list = firstPageDbService.personalPerformanceRanking(dateUnit, accountId, combination);

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                PerformanceRankingVO t = list.get(i);
                if (t.getAccountId().equals(userAccount.getAccountId())) {
                    ranking = t.getRowNum();
                }
            }
        }

        map.put("list", list);
        map.put("ranking", ranking);
        return map;
    }

    /**
     * 首页统计个人业绩排行榜
     * @param dateType 1年 2年月
     * @param combination dateType 1 2021  2 202101
     * @return
     */
    /*@Override
    public String personalPerformanceRanking(String dateType,String combination) {
        Integer dateUnit = 0;
        String ranking = "0";
        Map<String,Object> map = new HashMap<>();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (!StringUtils.isBlank(dateType)) {
            if ("1".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("2".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
        }

        List<PerformanceRankingVO> list = firstPageDbService.personalPerformanceRanking(dateUnit, accountId, combination);
        if (list != null && list.size() > 0) {
            for (int i =0; i < list.size(); i++) {
                PerformanceRankingVO t = list.get(i);
                if (t.getAccountId().equals(userAccount.getAccountId())) {
                    ranking = t.getRowNum();
                }
            }
        }

        return ranking;
    }*/

    /**
     * 首页统计个人业绩走势图
     *
     * @return
     */
    @Override
    public PerformanceVO performanceTrend() {


        Map<String, BigDecimal> thisMap = null;
        Map<String, BigDecimal> lastMap = null;

        //今年统计个人业绩
        List<PerformanceStatisticsVO> thisList = null;
        //去年统计个人业绩
        List<PerformanceStatisticsVO> lastList = null;

        //今年一年的月份
        List<String> thisYearMonth = getInitTime(0);

        //去年一年的月份
        List<String> lastYearMonth = getInitTime(1);
        List<String> lastMonthList = lastYearMonth.subList(0, 12);

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        if (!rs) {
            //今年统计个人业绩
            thisList = firstPageDbService.thisPerformanceTrend(userAccount.getAccountId(), thisYearMonth.get(0), thisYearMonth.get(thisYearMonth.size() - 1));
            //去年统计个人业绩
            lastList = firstPageDbService.lastPerformanceTrend(userAccount.getAccountId(), lastMonthList.get(0), lastMonthList.get(lastMonthList.size() - 1));
        }

        Map<String, BigDecimal> map = lastList.stream().collect(Collectors.toMap(PerformanceStatisticsVO::getTime, PerformanceStatisticsVO::getOrderActualTotalAmount));

        ArrayList<PerformanceStatisticsVO> vos = new ArrayList<>();
        for (String ymStr : lastMonthList) {
            BigDecimal bigDecimal = map.get(ymStr);
            PerformanceStatisticsVO vo = new PerformanceStatisticsVO();
            if (bigDecimal == null) {
                vo.setTime(ymStr);
                vo.setOrderActualTotalAmount(new BigDecimal(0));
            } else {
                vo.setTime(ymStr);
                vo.setOrderActualTotalAmount(bigDecimal);
            }
            vos.add(vo);
        }
        lastList = vos;

        if (!CollectionUtils.isEmpty(thisList)) {
            thisMap = thisList.stream()
                    .collect(Collectors.toMap(PerformanceStatisticsVO::getTime, amount -> Optional.ofNullable(amount.getOrderActualTotalAmount()).orElse(new BigDecimal("0"))));
        }
        if (!CollectionUtils.isEmpty(lastList)) {
            lastMap = lastList.stream()
                    .collect(Collectors.toMap(PerformanceStatisticsVO::getTime, amount -> Optional.ofNullable(amount.getOrderActualTotalAmount()).orElse(new BigDecimal("0"))));
        }

        List<BigDecimal> thisOrderActualTotalAmountList = Lists.newArrayList();
        List<BigDecimal> lastOrderActualTotalAmountList = Lists.newArrayList();

        for (String time : thisYearMonth) {
            if (Objects.nonNull(thisMap)) {
                BigDecimal orderActualTotalAmount = Optional.ofNullable(thisMap.get(time)).orElse(new BigDecimal("0"));
                thisOrderActualTotalAmountList.add(orderActualTotalAmount);
            } else {
                thisOrderActualTotalAmountList.add(new BigDecimal("0"));
            }
        }

        for (String time : lastMonthList) {
            if (Objects.nonNull(lastMap)) {
                BigDecimal orderActualTotalAmount = Optional.ofNullable(lastMap.get(time)).orElse(new BigDecimal("0"));
                lastOrderActualTotalAmountList.add(orderActualTotalAmount);
            } else {
                lastOrderActualTotalAmountList.add(new BigDecimal("0"));
            }
        }

        PerformanceVO performanceVO = new PerformanceVO();
        performanceVO.setThisTime(thisYearMonth);
        performanceVO.setThisPerformance(thisOrderActualTotalAmountList);
        performanceVO.setLastTime(lastMonthList);
        performanceVO.setLastPerformance(lastOrderActualTotalAmountList);

        return performanceVO;
    }

    /**
     * 产品成交排行榜
     *
     * @param dateType    1年 2年月
     * @param combination dateType 1 2021  2 202101
     * @return
     */
    @Override
    public List<ProductVO> productTurnoverList(String dateType, String combination) {
        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("1".equals(dateType)) {
                //年
                dateUnit = 1;
            }
            if ("2".equals(dateType)) {
                //年月
                dateUnit = 2;
            }
        }

        return firstPageDbService.productTurnoverList(dateUnit, combination);
    }

    /**
     * 二级管理首页统计信息
     *
     * @param dateType thisWeek 本周 lastWeek 上周 lastMonth 上月 thisMonth 本月
     * @return
     */
    @Override
    public Map<String, Object> adminFirstPageContent(String dateType) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> map = new HashMap<>();

        Integer dateUnit = 0;
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("lastMonth".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 4;
            }
            if ("lastWeek".equals(dateType)) {
                //上周
                dateUnit = 5;
            }

        }

        //二级管理业绩排名
        RankingVO rankingVO = firstPageDbService.adminSelectRanking(userAccount.getCompanyId(), dateUnit);
        RankingVO rankingVOLast = firstPageDbService.adminSelectRanking(userAccount.getCompanyId(), dateUnit + 1);


        //二级管理会员数量
        Integer customerMembershipNumber = firstPageDbService.adminSelectCustomerMembershipNumber(userAccount.getCompanyId(), dateUnit);
        if (customerMembershipNumber == null) {
            customerMembershipNumber = 0;
        }
        Integer customerMembershipNumberLast = firstPageDbService.adminSelectCustomerMembershipNumber(userAccount.getCompanyId(), dateUnit + 1);
        if (customerMembershipNumberLast == null) {
            customerMembershipNumberLast = 0;
        }
        Integer customerMembershipNumberTrend = compare(customerMembershipNumber, customerMembershipNumberLast);

        //二级管理业绩金额
        BigDecimal performanceAmount = firstPageDbService.adminSelectperformanceAmount(userAccount.getCompanyId(), dateUnit);
        if (performanceAmount == null) {
            performanceAmount = new BigDecimal(0);
        }
        BigDecimal performanceAmountLast = firstPageDbService.adminSelectperformanceAmount(userAccount.getCompanyId(), dateUnit + 1);
        if (performanceAmountLast == null) {
            performanceAmountLast = new BigDecimal(0);
        }
        Integer performanceAmountTrend = compareBigDecimal(performanceAmount, performanceAmountLast);


        //二级管理会员增长率
        BigDecimal membershipGrowthRate = firstPageDbService.selectMembershipGrowthRate(userAccount.getCompanyId(), dateUnit);
        if (membershipGrowthRate == null) {
            membershipGrowthRate = new BigDecimal(0);
        }
        BigDecimal membershipGrowthRateLast = firstPageDbService.selectMembershipGrowthRate(userAccount.getCompanyId(), dateUnit + 1);
        if (membershipGrowthRateLast == null) {
            membershipGrowthRateLast = new BigDecimal(0);
        }
        Integer membershipGrowthRateTrend = compareBigDecimal(membershipGrowthRate, membershipGrowthRateLast);

        //二级管理会员续费率
        BigDecimal membershipRenewalRate = firstPageDbService.selectMembershipRenewalRate(userAccount.getCompanyId(), dateUnit);
        if (membershipRenewalRate == null) {
            membershipRenewalRate = new BigDecimal(0);
        }
        BigDecimal membershipRenewalRateLast = firstPageDbService.selectMembershipRenewalRate(userAccount.getCompanyId(), dateUnit + 1);
        if (membershipRenewalRateLast == null) {
            membershipRenewalRateLast = new BigDecimal(0);
        }
        Integer membershipRenewalRateTrend = compareBigDecimal(membershipRenewalRate, membershipRenewalRateLast);

        Integer memberTurnoverCount = firstPageDbService.selectMemberTurnoverCount(userAccount.getCompanyId(), dateUnit);

        //二级管理会员流失率
        BigDecimal memberTurnoverRate = firstPageDbService.selectMemberTurnoverRate(userAccount.getCompanyId(), dateUnit);
        if (memberTurnoverRate == null) {
            memberTurnoverRate = new BigDecimal(0);
        }
        BigDecimal memberTurnoverRateLast = firstPageDbService.selectMemberTurnoverRate(userAccount.getCompanyId(), dateUnit + 1);
        if (memberTurnoverRateLast == null) {
            memberTurnoverRateLast = new BigDecimal(0);
        }
        Integer memberTurnoverRateTrend = compareBigDecimal(memberTurnoverRate, memberTurnoverRateLast);

        if (rankingVO == null || rankingVO.getRankingNumber() == null) {
            map.put("rankingNumber", 0);
        } else {
            map.put("rankingNumber", rankingVO.getRankingNumber());
        }

        Integer rankingNumber = (Integer) map.get("rankingNumber");
        if (rankingNumber == null) {
            rankingNumber = 0;
        }
        if ("thisMonth".equals(dateType) || "lastMonth".equals(dateType) || "thisWeek".equals(dateType) || "lastWeek".equals(dateType)) {
            //业绩排名
            if (rankingVOLast == null || rankingVOLast.getRankingNumber() == null) {
                Integer rankingNumberTrend = compare(rankingNumber, 0);
                map.put("rankingNumberTrend", rankingNumberTrend);
            } else {
                Integer rankingNumberTrend = compare(rankingNumber, rankingVOLast.getRankingNumber());
                map.put("rankingNumberTrend", rankingNumberTrend);
            }
            map.put("customerMembershipNumberTrend", customerMembershipNumberTrend);
            map.put("performanceAmountTrend", performanceAmountTrend);
            map.put("membershipGrowthRateTrend", membershipGrowthRateTrend);
            map.put("membershipRenewalRateTrend", membershipRenewalRateTrend);
            map.put("memberTurnoverRateTrend", memberTurnoverRateTrend);
        }

        //二级管理会员数量
        map.put("customerMembershipNumber", customerMembershipNumber);
        //二级管理业绩金额
        map.put("performanceAmount", performanceAmount);
        //二级管理会员增长率
        map.put("membershipGrowthRate", membershipGrowthRate);
        //二级管理会员续费率
        map.put("membershipRenewalRate", membershipRenewalRate);
        //二级管理会员流失率
        map.put("memberTurnoverRate", memberTurnoverCount);

        return map;
    }


    /**
     * 用户管理后台首页 统计信息
     */
    @Override
    public Map<String, Object> userFirstPageContent(String dateType) {
        return firstPageDbService.userFirstPageContent(dateType);
    }


    /**
     * 首页统计二级管理个人业绩金额走势图
     *
     * @return
     */
    @Override
    public PerformanceVO adminPerformanceTrend() {
        Map<String, BigDecimal> thisMap = null;
        Map<String, BigDecimal> lastMap = null;

        //今年统计个人业绩
        List<PerformanceStatisticsVO> thisList = null;
        //去年统计个人业绩
        List<PerformanceStatisticsVO> lastList = null;

        //今年一年的月份
        List<String> thisYearMonth = getInitTime(0);

        //去年一年的月份
        List<String> lastYearMonth = getInitTime(1);
        List<String> lastMonthList = lastYearMonth.subList(0, thisYearMonth.size());

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        if (!rs) {
            //今年统计个人业绩
            thisList = firstPageDbService.thisAdminPerformanceTrend(userAccount.getCompanyId(), thisYearMonth.get(0), thisYearMonth.get(thisYearMonth.size() - 1));
            log.info("thisList =====:{}", JSON.toJSONString(thisList));

            //去年统计个人业绩
            lastList = firstPageDbService.lastAdminPerformanceTrend(userAccount.getCompanyId(), lastMonthList.get(0), lastMonthList.get(thisYearMonth.size() - 1));
        }


        if (!CollectionUtils.isEmpty(thisList)) {
            thisMap = thisList.stream()
                    .collect(Collectors.toMap(PerformanceStatisticsVO::getTime, amount -> Optional.ofNullable(amount.getOrderActualTotalAmount()).orElse(new BigDecimal("0"))));
        }
        if (!CollectionUtils.isEmpty(lastList)) {
            lastMap = lastList.stream()
                    .collect(Collectors.toMap(PerformanceStatisticsVO::getTime, amount -> Optional.ofNullable(amount.getOrderActualTotalAmount()).orElse(new BigDecimal("0"))));
        }

        List<BigDecimal> thisOrderActualTotalAmountList = Lists.newArrayList();
        List<BigDecimal> lastOrderActualTotalAmountList = Lists.newArrayList();

        for (String time : thisYearMonth) {
            if (Objects.nonNull(thisMap)) {
                BigDecimal orderActualTotalAmount = Optional.ofNullable(thisMap.get(time)).orElse(new BigDecimal("0"));
                thisOrderActualTotalAmountList.add(orderActualTotalAmount);
            } else {
                thisOrderActualTotalAmountList.add(new BigDecimal("0"));
            }
        }

        for (String time : lastMonthList) {
            if (Objects.nonNull(lastMap)) {
                BigDecimal orderActualTotalAmount = Optional.ofNullable(lastMap.get(time)).orElse(new BigDecimal("0"));
                lastOrderActualTotalAmountList.add(orderActualTotalAmount);
            } else {
                lastOrderActualTotalAmountList.add(new BigDecimal("0"));
            }
        }

        PerformanceVO performanceVO = new PerformanceVO();
        performanceVO.setThisTime(thisYearMonth);
        performanceVO.setThisPerformance(thisOrderActualTotalAmountList);
        performanceVO.setLastTime(lastMonthList);
        performanceVO.setLastPerformance(lastOrderActualTotalAmountList);

        return performanceVO;
    }

    /**
     * 首页统计二级管理业绩排行榜
     *
     * @param dateType thisMonth 本月 lastMonth 上月   thisYear 今年  lastYear 去年
     * @return
     */
    @Override
    public List<PerformanceRankingVO> adminCompanyPerformanceRanking(String dateType) {
        String startDate = null;
        String endDate = null;
        String formatStr = "yyyy-MM";

        Date date = new Date();


        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                String format = DateUtil.format(date, formatStr);
                startDate = format;
                endDate = format;
            }
            Calendar calendar = Calendar.getInstance();
            if ("lastMonth".equals(dateType)) {
                //上个月
                calendar.add(Calendar.MONTH, -1);
                String format = DateUtil.format(calendar.getTime(), formatStr);
                startDate = format;
                endDate = format;
            }
            if ("thisYear".equals(dateType)) {
                //今年
                String format = DateUtil.format(date, formatStr);
                String year = DateUtil.getYear();
                startDate = year + "-01";
                endDate = format;
            }
            if ("lastYear".equals(dateType)) {
                //去年
                calendar.add(Calendar.YEAR, -1);
                String format = DateUtil.format(calendar.getTime(), "yyyy");
                startDate = format + "-01";
                endDate = format + "-12";
            }

        }
        // 查询预设时间内的数据
        List<PerformanceRankingVO> performanceRankingVOS = firstPageDbService.adminCompanyPerformanceRank(startDate, endDate);

        // 提取 公司id 获取 ids
        if (performanceRankingVOS.size() <= 0) {
            return new ArrayList<>();
        }
        List<String> companyIds = performanceRankingVOS.stream().map(PerformanceRankingVO::getCompanyId).collect(Collectors.toList());
        // 获取归属到该公司的所有业务员的充值金额。

        // 根据公司id 累加到该公司的业绩金额中。
        if (companyIds.size() > 0) {
            List<CompanyPayMoneyVO> payMoneyByCompanyId = customerPayCustomMapper.getPayMoneyByCompanyId(companyIds, startDate, endDate);
            for (CompanyPayMoneyVO payMoneyVO : payMoneyByCompanyId) {
                for (PerformanceRankingVO vo : performanceRankingVOS) {
                    //如果 当前业务员本月办理了充值业务，则将充值金额添加到该业务员的业绩中
                    if (payMoneyVO != null && payMoneyVO.getPayMoney() != null && payMoneyVO.getCompanyId().equals(vo.getCompanyId()) && payMoneyVO.getPayMoney().doubleValue() > 0) {
                        vo.setContractActualTotalAmount(vo.getContractActualTotalAmount().add(payMoneyVO.getPayMoney()));
                    }
                }
            }
        }

        List<PerformanceRankingVO> collect = performanceRankingVOS.stream().sorted().collect(Collectors.toList());

        return collect;
    }

    /**
     * 首页统计二级管理分公司下的业绩排行榜
     *
     * @param dateType thisMonth 本月 lastMonth 上月   thisYear 今年  lastYear 去年 thisWeek 本周  lastWeek 上周
     * @return
     */
    @Override
    public List<PerformanceRankingVO> adminCompanyPersonalPerformanceRanking(String dateType) {
        Integer dateUnit = 0;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("lastMonth".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 3;
            }
            if ("lastWeek".equals(dateType)) {
                //上周
                dateUnit = 4;
            }
            if ("thisYear".equals(dateType)) {
                //今年
                dateUnit = 5;
            }
            if ("lastYear".equals(dateType)) {
                //去年
                dateUnit = 6;
            }
        }

        return firstPageDbService.adminCompanyPersonalPerformanceRanking(dateUnit, userAccount.getCompanyId(), accountId);
    }

    /**
     * 首页统计二级管理分公司下的业绩排行榜
     *
     * @param dateType thisMonth 本月 lastMonth 上月   thisYear 今年  lastYear 去年 thisWeek 本周  lastWeek 上周
     * @return
     */
    @Override
    public List<PerformanceRankingVO> adminCompanyPersonalPerformanceRank(String dateType, String seniority) {
        Integer dateUnit = 0;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        if (!StringUtils.isBlank(dateType)) {
            if ("thisMonth".equals(dateType)) {
                //本月
                dateUnit = 1;
            }
            if ("lastMonth".equals(dateType)) {
                //上个月
                dateUnit = 2;
            }
            if ("thisWeek".equals(dateType)) {
                //本周
                dateUnit = 3;
            }
            if ("lastWeek".equals(dateType)) {
                //上周
                dateUnit = 4;
            }
            if ("thisYear".equals(dateType)) {
                //今年
                dateUnit = 5;
            }
            if ("lastYear".equals(dateType)) {
                //去年
                dateUnit = 6;
            }
        }
        List<PerformanceRankingVO> performanceRankingVOS = new ArrayList<>();
        List<CustomerPayMoneyVO> payMoneyByAccountIdAndDateType = new ArrayList<>();
        // 判断是否传了司龄
        if (seniority != null && !"".equals(seniority) && !"入职区间".equals(seniority)) {
            // 根据司龄，公司id确认员工id，通过员工id、时间字段直接查询对应员工的业绩。
            List<String> accountIds = userAccountCustomMapper.getAccountIdByCompanyIdAndSeniority(userAccount.getCompanyId(), seniority);
            if (accountIds == null || accountIds.size() <= 0) {
                return performanceRankingVOS;
            }
            performanceRankingVOS = firstPageDbService.adminCompanyPersonalPerformanceRank(dateUnit, userAccount.getCompanyId(), accountIds);

            // 解析前一步查询到的员工ids，查询对应员工完成的充值业务。
            payMoneyByAccountIdAndDateType = customerPayCustomMapper.getPayMoneyByAccountIdAndDateType(accountIds, dateUnit);
        } else {
            // 根据时间字段查询该公司所有员工的业绩。
            performanceRankingVOS = firstPageDbService.adminCompanyPersonalPerformanceRank(dateUnit, userAccount.getCompanyId(), null);
            List<String> accountIds = performanceRankingVOS.stream().map(PerformanceRankingVO::getAccountId).collect(Collectors.toList());

            if (accountIds.size() > 0) {
                // 解析前一步查询到的员工ids，查询对应员工完成的充值业务。
                payMoneyByAccountIdAndDateType = customerPayCustomMapper.getPayMoneyByAccountIdAndDateType(accountIds, dateUnit);
            }

        }

        // 根据根据员工id将其完成的充值金额，累加到业绩数据中。
        if (payMoneyByAccountIdAndDateType.size() > 0) {
            for (CustomerPayMoneyVO payMoneyVO : payMoneyByAccountIdAndDateType) {
                for (PerformanceRankingVO vo : performanceRankingVOS) {
                    //如果 当前业务员本月办理了充值业务，则将充值金额添加到该业务员的业绩中
                    if (payMoneyVO != null && payMoneyVO.getPayMoney() != null && payMoneyVO.getAccountId().equals(vo.getAccountId())) {
                        vo.setContractActualTotalAmount(vo.getContractActualTotalAmount().add(payMoneyVO.getPayMoney()));
                    }
                }
            }
        }
        List<PerformanceRankingVO> sorted = performanceRankingVOS.stream().sorted().collect(Collectors.toList());

        return sorted;
    }


    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }


    /**
     * 获取初始化时间-联系人折线图X轴 yyyy-MM
     *
     * @return
     */
    private static List<String> getInitTime(int a) {
        DateTime dateTime = null;
        Calendar calendar = Calendar.getInstance();
        if (a == 1) {
            calendar.add(Calendar.YEAR, -1);
        }

        Date lastTime = calendar.getTime();
        Date thisTime = DateUtil.getSysDate();
        if (a == 1) {
            dateTime = DateUtils.beginOfYear(lastTime);
        } else {
            dateTime = DateUtils.beginOfYear(thisTime);
        }


        List<DateTime> dateTimes = DateUtils.rangeToList(dateTime, DateUtil.getSysDate(), DateField.MONTH);
        return dateTimes.stream().map(date -> DateUtil.formatDate(date, DateUtils.DATE_FORMAT_YYYY_MM))
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getSeniority() {
        return userAccountCustomMapper.getSeniority();
    }

    @Override
    public Boolean firstPageSalesman() {
        List<PerformanceRankingVO> list = firstPageDbService.personalPerformanceRanking(0, accountId, "");
        String key = RedisPrefix.SALESMAN_TOP_THIRTY;
        ValueRMapper.setRedisString(redisTemplate, key, JSON.toJSONString(list));
        return true;
    }

    /**
     * 首页统计按年个人业绩
     */
    @Override
    public Boolean firstPageSalesmanByYear() {
        Set<String> list = new HashSet<>();
        List<PerformanceRankingVO> dtos = firstPageDbService.firstPageSalesmanByYear();
        if (dtos != null && dtos.size() > 0) {
            for (PerformanceRankingVO sa : dtos) {
                list.add(sa.getArriveTime());
            }
        }
        for (String date : list) {
            List<PerformanceRankingVO> dList = new ArrayList<>();
            for (PerformanceRankingVO sa : dtos) {
                if (date.equals(sa.getArriveTime())) {
                    dList.add(sa);
                }
            }
            String key = RedisPrefix.SALESMAN_TOP_YEAR_THIRTY + date;
            ValueRMapper.setRedisString(redisTemplate, key, JSON.toJSONString(dList));
        }
        return true;
    }

    /**
     * 首页统计按年月个人业绩
     */
    @Override
    public Boolean firstPageSalesmanByMonth() {
        Set<String> list = new HashSet<>();
        List<PerformanceRankingVO> dtos = firstPageDbService.firstPageSalesmanByMonth();
        if (dtos != null && dtos.size() > 0) {
            for (PerformanceRankingVO sa : dtos) {
                list.add(sa.getArriveTime());
            }
        }
        for (String date : list) {
            List<PerformanceRankingVO> dList = new ArrayList<>();
            for (PerformanceRankingVO sa : dtos) {
                if (date.equals(sa.getArriveTime())) {
                    dList.add(sa);
                }
            }
            String key = RedisPrefix.SALESMAN_TOP_MONTH_THIRTY + date;
            ValueRMapper.setRedisString(redisTemplate, key, JSON.toJSONString(dList));
        }
        return true;
    }
}
